package org.taru.ems.common.intercepter;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.taru.ems.common.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * token验证拦截器
 */
@Slf4j
@Component
public class TokenVerificationIntercepter implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;
    @Value("${my.tokenKey}")
    String tokenKey;
    @Value("${my.enableTokenValid}")
    boolean  isEnableValid;

    @Value("${my.enableRedisToken}")
    Boolean   enableRedisToken;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("正在请求接口:{}",request.getRequestURL());
       //token验证开关
        if(!isEnableValid){
            return true;
        }
        //从请求头中获取 token
        String token =request.getHeader(tokenKey);
        if(token!=null){
                //验证token的合法性
            boolean  isValid =jwtUtil.validateToken(token);
            if(isValid){
                return true;
            }

        }
        //告诉前端 你没有令牌 通过http状态吗 401
        response.setStatus(401);
        response.setContentType("text/plain;charset=utf-8");
        response.getWriter().write("没有有效的token令牌，请重新登录");
        return false;
    }
}
